<template>
  <div class='myMessage'>
    <div style="position:relative">
      <div class='titleTop'>
        <img style="position:relative;top: 6px;width: 12px;height: 18px; margin-right: 10px;" src="~@/assets/images/myInfo/info_phonesmile.png" alt="">
        <div>{{phoneReturnShow}}</div>
      </div>
      <img width='100%' src="~@/assets/images/myInfo/info_top.png" alt="">
    </div>
    <div class="midContent">
      <div class="module">
        <van-cell title="姓名" v-model="name"  />
      </div>
      <div class="module">
        <!-- <van-cell title="手机号" v-model="phoneReturn" /> -->
        <van-cell title="证件类型" v-model="type_card"  />
        <van-cell title="证件号码" v-model="id_card" />
        <div  v-show="showCard" v-for="(item,index) in platenumbers" :key="index">
          <van-cell title="车牌号" v-if='index==0' v-model="platenumbers[0].platenumber"/>
          <van-cell title="" v-else v-model="item.platenumber"/>
        </div>
      </div>
      <div class="module rightStyle">
        <van-field label="邮箱地址" v-model="email" placeholder="请输入邮箱" input-align="right"  />
        <van-field label="通讯地址" readonly v-model="information_address_all" @click="getAddress" placeholder="请选择通讯地址"  is-link />
      </div>
      <div class="module">
        <van-field placeholder="请输入详细地址" v-model="addressDetail" style="height:80px" type="textarea" />
      </div>
      <div v-if='jigouShow'> 
          <div v-if='invitation' class="module" @click='invitationBtn'><van-cell title="邀请注册" is-link /></div>
          <div class="module">
              <van-cell v-if='jigouInShow' title="机构" v-model="comName" />
              <van-cell title="更新机构" @click='comNameUpdate'  is-link/>
          </div> 
      </div>
      <div class="submitMessage" @click="submitMessage">保存</div>
      <div style="width:100px;margin:0 auto;padding:15px;font-size:15px;color:red;text-align:center" @click="loginOut">退出登录</div>
    </div>
    <div class='showFlag' v-show="showPicker" @click.self="showPicker = false">
      <van-dropdown-menu direction="up"  :overlay="false" style="position:fixed;bottom:0;left:0;right:0">
        <van-dropdown-item v-model="province" :title="provinceName" :options="province_list" @change="onChange('province')" />
        <van-dropdown-item v-model="city" :title="cityName" :options="city_list" @change="onChange('city')" />
        <van-dropdown-item v-model="area" :disabled="disabledArea" :title="areaName" :options="area_list" @change="onChange('area')" />
      </van-dropdown-menu>
    </div>
  </div>
</template>
<script lang="ts">
import '../../style/reservaIndex_index.css';
import 'vant/lib/dialog/style';
import 'vant/lib/field/style';
import 'vant/lib/picker/style';
import 'vant/lib/cell/style';
import 'vant/lib/overlay/style';
import 'vant/lib/dropdown-menu/style';
import 'vant/lib/dropdown-item/style';
import { Dialog , Field, Picker, Cell,Overlay,DropdownMenu, DropdownItem } from 'vant';
import { Component, Vue, Prop } from 'vue-property-decorator';
import { cloudApi } from '@/api/indexApi';
import { Alert } from '@/utils';
import Header from '@/components/Header.vue';
import { values } from 'lodash';
Component.registerHooks(['beforeRouteUpdate', 'beforeRouteLeave', 'beforeRouteLeave']);
@Component({
  components: { Header,
    [Dialog.name]: Cell, 
    [Field.name]: Field,
    [Picker.name]: Picker,
    [Overlay.name]: Overlay,
    [Cell.name]: Cell,
    [DropdownMenu.name]: DropdownMenu,
    [DropdownItem.name]: DropdownItem,
     },
})
export default class MainPage extends Vue {
  userId: string = '';
  informationId:any = '';
  bind_id_Card = ''
  bind_party_Id = ''
  bind_type_Card = ''
  phoneReturn = ''
  phoneReturnShow=''
  platenumbers=[]
  email=''
  showCard = true
  showPicker = false
  invitation:any=false// 邀请注册是否显示
  jigouShow:any=false;//机构三块显示
  jigouInShow:any=false;//机构
  name = ''
  id_card = ''
  type_card = ''
  province_list:any = []
  city_list:any = []
  area_list:any = []
  province = ''
  city = ''
  area = ''
  provinceName = '请选择省'
  cityName = '请选择市'
  areaName = '请选择区'
  disabledArea = false
  provinceCheck = ''
  information_address_all = ''
  addressDetail = ''
  openId=''
  unionId=''
  token:any=''
  comName:any=''//机构名称
  invitationCode:any=''//邀请码
  nameJigou:any=''//销售人员名称
  userIdJigou:any=''//机构userId
  idCardJigou:any=''//机构身份证号
  idTypeJigou:any=''//机构身份类型
  cardTypeList:any=[ 
    {value:'01',text: '居民身份证'},
    {value:'02',text: '居民户口簿'},
    {value:'03',text: '驾驶证'},
    {value:'04',text: '中国因公护照'},
    {value:'05',text: '中国因私护照'},
    {value:'06',text: '往来港澳通行证'},
    {value:'07',text: '大陆居民往来台湾通行证'},
    {value:'08',text: '军官证/警官证'},
    {value:'09',text: '士兵证'},
    {value:'10',text: '军官离退休证'},
    {value:'11',text: '港澳居民来往内地通行证'},
    {value:'12',text: '台湾居民来往大陆通行证'},
    {value:'13',text: '香港身份证'},
    {value:'14',text: '澳门身份证'},
    {value:'15',text: '台湾身份证'},
    {value:'16',text: '外国护照'},
    {value:'17',text: '外国人永久居留证'},
    {value:'18',text: '港澳台居民居住证'},
    {value:'29',text: '其它个人证件'},
  ]
  created() {
    document.title = '个人信息'
    //this.getSecritUserId()
    //this.myInformation_getbind()
    const userDateOne:any = sessionStorage.getItem('getUserDate')
    const userDateTwo:any = sessionStorage.getItem('userData')
    const userDate1:any = JSON.parse(userDateOne)
    const userDate2:any = JSON.parse(userDateTwo)
    this.informationId = userDate1.id
    this.bind_id_Card = userDate1.id_card
    this.bind_party_Id = userDate1.party_id
    this.bind_type_Card = userDate1.type_card
    this.openId = userDate2.openId
    this.userId = userDate2.userId
    this.unionId = userDate2.unionId
    this.noAllBind()
    // this.getToken()
  }
  mounted(){
  }
  //获取加密ID
  getSecritUserId(){
    var data = AESEncode({
                userid: this.userId
            })
    cloudApi.desStringUserId({result:data}).then(res => {
      var Res = AESDecode(res.data.result)
      this.userId = Res.userid
    })
  }
  //查询是否为半绑定,如果半绑定不显示车牌，如果绑定，显示车牌
  noAllBind(){
    const data = {
      datasource: "zgs",
      id: this.informationId,
      open_id: this.openId,
      menuID: "",
      mark: ""
    }
    cloudApi.toQuery(data).then(res => {
      if(res.status == 200){
        if(res.data.result == "bindPlatenumber"){
          this.showCard = false
        }else{
          this.jigouShow=true//机构显示
        }
        var data = AESEncode({
          id: this.informationId,
          idCard: this.bind_id_Card,
          partyId: this.bind_party_Id,
          typeCard: this.bind_type_Card
        });
        this.getDetail(data)
      }
    })
  }
  getToken(){//获取人员信息的touken
  let data={ mobile:this.phoneReturn}
   cloudApi.getToken(data).then(res => {
       if(res.data.result.header.statusCode == '00000000'){
        console.log('gettoken',res.data.result.body)
        this.token =res.data.result.body.token 
        this.nameJigou =res.data.result.body.userName  
        this.userIdJigou=res.data.result.body.userId
        this.idCardJigou=res.data.result.body.userCardNo
        this.idTypeJigou=res.data.result.body.userCardType
        this.getpersonInfo() 
      }else{    
        Dialog.alert({ title: '温馨提示', message: res.data.result.header.message })
      }
    })
  }
  getpersonInfo(){//获取安心通销售人员信息
  let _this =this
  let data={
    flag: "1",
    token: this.token,
    userId:this.userIdJigou,
   }
   cloudApi.peacequeryUserInfo(data).then(res => {
     console.log('返参',res)
      if(res.data.result.header.statusCode == '00000000'){
        if(res.data.result.body){//有数据
           _this.nameJigou =res.data.result.body.userInfo.userName
          if(res.data.result.body.bindStatus == 1){//已绑定
           _this.invitation=true;//邀请注册显示
           _this.jigouInShow=true;//机构显示
           if(res.data.result.body.channelSource=='1'){//销售公司
              _this.comName=res.data.result.body.userInfo.comName
           }else if(res.data.result.body.channelSource=='0'){//urm系统
             _this.comName=''//机构值为空
              // Dialog.alert({ title: '温馨提示', message: '销管系统未查询到该用户信息，请联系相关人员确认' })
           }
          }else if(res.data.result.body.bindStatus==0){//未绑定 更新机构显示
            _this.invitation=false;//邀请注册不显示
            _this.jigouInShow=false;//机构不显示
          }
        }else{//无数据
          _this.invitation=false;//邀请注册不显示
          _this.jigouInShow=false;//机构不显示
        }
      }else{
        _this.invitation=false;//显示邀请注册
        _this.comName = '';
        Dialog.alert({ title: '温馨提示', message: res.data.result.header.message })
      }
    })
  }
  comNameUpdate(){//机构更新按钮
  let data={
     idCard: this.idCardJigou,
     mobile: this.phoneReturn,
     idType: this.idTypeJigou,
     userId: this.userIdJigou
   }
   cloudApi.peaceOfMind(data).then(res => {
     console.log('返参',res)
     if(res.data.result.header.statusCode == '00000000'){
       if(res.data.result.body.channelSource == 1){
         this.comName =res.data.result.body.comName
       }else if(res.data.result.body.channelSource == 0){
         this.comName = '';
         Dialog.alert({ title: '温馨提示', message: '销管系统未查询到该用户信息，请联系相关人员确认' })
       }
     }else{
       this.comName = '';
       Dialog.alert({ title: '温馨提示', message: res.data.result.header.message })
     }
    })
  }
  //获取个人信息详情
  getDetail(data:any){
    cloudApi.getMyBussinessCardDetailURL({result:data}).then(res => {
      if(res.status == 200){
        var Res = AESDecode(res.data.result)
        if(Res.result == 'error'){
          Alert({ message: Res.msg })
        }else{
          console.log("RES",Res)
          this.a(Res)
          this.name = Res.result.name.substring(0, Res.result.name.length-1)+"*";
          var cardID_valueFirst = Res.result.id_card.substring(0, 10);
          var cardID_valueSecond = Res.result.id_card.substring(Res.result.id_card.length - 2, Res.result.id_card.length);
          if (Res.result.id_card.length == "15") {
            Res.result.id_card = cardID_valueFirst + "***" + cardID_valueSecond; //对证件号码做****处理
          } else {
            Res.result.id_card = cardID_valueFirst + "******" + cardID_valueSecond; //证件号码
          }
          this.id_card = Res.result.id_card
          // this.type_card = Res.result.type_card
          this.cardTypeList.forEach((item:any) => {
            if (item.value === Res.result.type_card) {
              this.type_card = item.text;
            }
          });
        }
      }
    })
  }
  //详细信息数据处理
  a(data:any) {
    console.log("a",data)
    this.phoneReturn = data.result.mobile_Phone
    this.phoneReturnShow = this.phoneReturn.substring(0, 3)+'****'+ this.phoneReturn.substring(this.phoneReturn.length-4)
    this.platenumbers = data.result.platenumbers //车牌号脱敏
    const stars = ["", "*", "**", "***", "****", "*****", "******"]
    for (var i = 0; i < this.platenumbers.length; i++) {
        if (this.platenumbers[i].platenumber.length < 8) {
            this.platenumbers[i].platenumber = this.platenumbers[i].platenumber.substring(0, 3) + stars[this.platenumbers[i].platenumber.length - 4] + this.platenumbers[i].platenumber.substring(this.platenumbers[i].platenumber.length - 1, this.platenumbers[i].platenumber.length)
        } else {
            this.platenumbers[i].platenumber = this.platenumbers[i].platenumber.substring(0, 4) + stars[this.platenumbers[i].platenumber.length - 5] + this.platenumbers[i].platenumber.substring(this.platenumbers[i].platenumber.length - 1, this.platenumbers[i].platenumber.length)
        }
    }
    this.email = data.result.email //邮箱
    const a:any = data.result.address.indexOf("*");
    this.information_address_all = data.result.address.slice(0,a) //地址
    this.addressDetail = data.result.address.slice(a+1)
    this.getToken()//机构token
    console.log(this.information_address_all+' '+this.addressDetail)
  };
  //查询名片信息
  myInformation_getbind(){
    const data = {
        openid: this.openId,
        unionid: ""
    }
    cloudApi.getMyBussinessCardURL(data).then(res => {
      if(res.status = 200){
        if(res.data.result.length !== 0){
          this.informationId = res.data.result[0].id
          this.bind_id_Card = res.data.result[0].id_card
            //取出party_id
          this.bind_party_Id = res.data.result[0].party_id
            //取出type_card
          this.bind_type_Card = res.data.result[0].type_card
          console.log(res)
        }
      }
    })
  }
  invitationBtn(){//邀请按钮
    this.$router.push({path: 'inviteRegister',query:{name:this.nameJigou,token:this.token,userId:this.userIdJigou}}); 
  }
  //获取地址
  getAddress(){
    this.province_list = []
    this.showPicker = true
    const data = {
      code:''
    }
    cloudApi.queryAddressInfoURL(data).then(res=>{
      res.data.result.forEach((e:any,index:any) => {
        this.province_list.push({"text":e.name,"value":index,"code":e.code})
      });
    })
    console.log(this.province_list)
  }
  onChange(value:any){
    if(value == "province"){
      const item = this.province_list[this.province]
      this.provinceName = item.text
      this.provinceCheck = item.code
      this.city_list = []
      this.area_list = []
      this.city = ''
      this.cityName = '请选择市'
      this.area = ''
      this.areaName = '请选择区'
      cloudApi.queryAddressInfoURL({code:item.code}).then(res=>{
        res.data.result.forEach((e:any,index:any) => {
          this.city_list.push({"text":e.name,"value":index,"code":e.code})
        });
      })
      console.log(this.city_list)
    }else if(value == "city"){
      const item = this.city_list[this.city]
      this.area_list = []
      this.cityName = item.text
      this.area = ''
      this.areaName = '请选择区'
      if(this.provinceCheck == "110000" || this.provinceCheck == "120000" || this.provinceCheck == "500000" || this.provinceCheck == "310000"){
        this.disabledArea = true
        this.information_address_all = `${this.provinceName}`+' '+`${this.cityName}`
        this.showPicker = false
      }else{
        this.disabledArea = false
        cloudApi.queryAddressInfoURL({code:item.code}).then(res=>{
          res.data.result.forEach((e:any,index:any) => {
            this.area_list.push({"text":e.name,"value":index,"code":e.code})
          });
        })
        console.log(this.area_list)
      }
    } else if(value == "area"){
      const item = this.area_list[this.area]
      this.areaName = item.text
      this.information_address_all = `${this.provinceName}`+' '+`${this.cityName}`+' '+`${this.areaName}`
      this.showPicker = false
    }
  }
  submitMessage(){
    if(!/^[A-Za-z0-9]+([_\.][A-Za-z0-9]+)*@([A-Za-z0-9\-]+\.)+[A-Za-z]{2,6}$/.test(this.email)){
      Alert({ message:"请输入正确的邮箱"})
      return;
    }
    const data = {
      datasource: 'zgs',
      id:this.informationId,
      openid: this.openId,
      email: this.email,
      address: this.information_address_all  +'*'+ this.addressDetail
    } 
    let _this =this;
    console.log(data)
    cloudApi.saveEAInfoURL(data).then(res => {
      if (res.data.result == "1") {
        Dialog.alert({title: '温馨提示',message: '保存成功'}).then(() => {
          _this.jifensaveToRedis()
          _this.$router.push({path: 'personalCard'}); 
        });
      } else {
        Alert({ message:'资料修改失败，请与客服人员联系或致电4008695519咨询！'})
      }
    })
  }
  jifensaveToRedis(){//维护地址信息 积分埋点
     const data = {
      userId: this.userIdJigou,
      sysId:'',//系统id
      operationCode:'1381906378954706944'//操作id
    } 
    cloudApi.saveToRedis(data).then(res => {
      if (res.data.flag == "1") {
        console.log('基础分/维护地址信息 成功')
      }
    })
  }
  loginOut(){
    let _this =this
    const data = {
      "id":this.informationId,
      "phone": this.phoneReturn, //手机号
      "datasource": 'zgs' //分公司标识
    }
    cloudApi.submitUnbindIntergrationUser(data).then(res => {
       if (res.data.result == 'success') {
          Dialog.confirm({ title: '温馨提示',message: '是否确认退出？'}) 
          .then(() => { 
             _this.$router.push({path: 'checkPhoneInfo', query: {
              unionId:_this.unionId,
              openId: _this.openId,
              route:JSON.stringify({path:'personalCard'})
          },}); 
            // this.$router.push("checkPhoneInfo") //跳转到手机号录入页面
          }).catch(() => {});  
        } else {
            Alert({ message:"退出失败"})
        }
    })
  }
}
</script>
<style lang="less" scoped>
.myMessage{
  background:#FAF9F7;
  width: 100%;
  min-height: 100%;
  position: relative;
  top:0;
  bottom: 0;
  left: 0;
  right: 0;
  .titleTop{
    position: absolute;
    color: #fff;
    font-size: 20px;
    padding: 50px 20px 0;
    display: flex;
  }
  .midContent{
    width: 94%;
    position: relative;
    left: 50%;
    transform: translateX(-50%);
    top:-15px;
  }
  .submitMessage{
    height: 36px;
    line-height: 36px;
    background: #00A08A;
    border-radius: 18px;
    margin:0 30px;
    color:#fff;
    font-size: 14px;
    text-align: center;
  }
  .module{
    margin-bottom: 15px;
    border-radius: 12px;
    overflow: hidden;
  }
  .rightStyle {
    /deep/.van-field__control{
      text-align: right;
  }
  }
  .van-cell{
    height:45px;
    line-height: 25px;
  }
  .showFlag{
    position: fixed;
    top: 0;
    left: 0;
    z-index: 1;
    width: 100%;
    height: 100%;
    background-color: rgba(0,0,0,.7);
  }
}
</style>

